// 实现一个插件
let Vue
class Store {
    constructor(options) {
        this.$options = options
        this._mutations = options.mutations
        this._actions = options.actions
        this.getters = {}
        Object.keys(options.getters).forEach(key => {
            Object.defineProperty(this.getters, key, {
                get: () => {
                    return options.getters[key](this.state)
                },
                enumerable: true
            })
        })
        this._vm = new Vue({
            data() {
                // 加上俩个$, 不让Vue做代理
                return {
                    $$state: options.state
                }
            }
        })
        this.commit = this.commit.bind(this)
        this.dispatch = this.dispatch.bind(this)
    }

    get state() {
        return this._vm._data.$$state
    }
    set state(v) {
        console.log("不能直接更改state, 请通过mutation修改")
    }

    // commit('add', 10)
    commit(type, payload) {
        const mutation = this._mutations[type]
        if (!mutation) {
            console.error("错误的mutation名称")
            return
        }
        mutation(this.state, payload)
    }
    dispatch(type, payload) {
        const action = this._actions[type]
        if (!action) {
            console.error("错误的action名称")
            return
        }
        action(this, payload)
    }
}
function install(_Vue) {
    Vue = _Vue
    // 注册$store
    Vue.mixin({
        beforeCreate() {
            if (this.$options.store) {
                Vue.prototype.$store = this.$options.store
            }
        }
    })
}
// { Store } 代表Vuex
export default { Store, install }